﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Cms.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Cms.Repositories;


[UseDI(ServiceLifetime.Scoped)]
public class CmsCustomLeaseLeaseRepository : Repository<CmsCustomLease, DefaultDbContext>
{
    public CmsCustomLeaseLeaseRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
    }

    public IPagedList<CmsCustomLease> GetCmsCustomLeases(CmsCustomLeaseQuery query, int pageIndex, int pageSize)
    {
        Sql sql = Sql.Builder;
        sql.Select("cms_custom_lease.id")
            .From("cms_custom_lease");
        sql.InnerJoin("cms_custom as p").On("p.id=cms_custom_lease.custom_id");
        sql.Where("cms_custom_lease.is_deleted=0");
        if (query.DealerId.HasValue)
            sql.Where("p.dealer_id=@0", query.DealerId.Value);
        if (query.Status.HasValue) 
            sql.Where("cms_custom_lease.status=@0", query.Status.Value);
        if (!string.IsNullOrEmpty(query.Keywords))
            sql.Where("(remark Like @0 or name like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
        sql.OrderBy("cms_custom_lease.create_dt DESC");
        var result = GetPagingEntities(pageSize, pageIndex, sql);
        return result;
    }

    public IEnumerable<CmsCustomLease> GetCmsCustomLeasesByDealerId(int dealerId)
    {
        //int areaVersion = EntityCacheService.GetAreaVersion("DealerId", dealerId);
        //return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
        //{
        //    return $"CmsCustomLeasesByDealerId:{dealerId}";
        //}, () =>
        //{
        //    Sql sql = Sql.Builder.Select("cms_custom_lease.id").From("cms_custom_lease");
        //    sql.InnerJoin("cms_custom as c on cms_custom_lease.custom_id=c.id");
        //    sql.Where("c.dealer_id=@0", dealerId);
        //    return sql;
        //});

        Sql sql = Sql.Builder.Select("cms_custom_lease.id").From("cms_custom_lease");
        sql.InnerJoin("cms_custom as c on cms_custom_lease.custom_id=c.id");
        sql.Where("c.dealer_id =@0", dealerId);
        return PopulateEntitiesByEntityIds(DbContext.Fetch<int>(sql));
    }

    public IEnumerable<CmsCustomLease> GetCmsCustomLeasesByDealerIds(IEnumerable<int> dealerIds)
    {
        if (dealerIds == null || dealerIds.Count() == 0)
            return Enumerable.Empty<CmsCustomLease>();
        Sql sql = Sql.Builder.Select("cms_custom_lease.id").From("cms_custom_lease");
        sql.InnerJoin("cms_custom as c on cms_custom_lease.custom_id=c.id");
        sql.Where("c.dealer_id in(@0)", dealerIds);
        return PopulateEntitiesByEntityIds(DbContext.Fetch<int>(sql));
    }
}
